<template>
  <span class="j-underline" :class="{ active: checked || modelValue }" @click.stop="">
    <slot></slot>
  </span>
</template>
<script>
import Hammer from "hammerjs";

export default {
  name: "HammerItem",

  props: {
    value: {
      type: Number,
    },
    modelValue: {
      type: Boolean,
      default: false,
    },
  },

  emits: ["change", "update:modelValue"],
  data() {
    return {
      hammer: null,
      checked: false,
      chandleHandles: [],
    };
  },

  mounted() {
    this.init();
  },

  beforeUnmount() {
    this.hammer.destroy();
  },
  methods: {
    change(checked) {
      this.checked = checked;
    },
    init() {
      this.hammer = new Hammer(this.$el);
      this.hammer.on("press tap", (e) => {
        e.srcEvent.stopPropagation();
        this.$emit("change", {
          value: this.value,
          checked: !this.checked || !this.modelValue,
        });
        this.chandleHandles.forEach((handle) => {
          handle({
            value: this.value,
            checked: !this.checked || !this.modelValue,
          });
        });
        this.$emit("update:modelValue", !this.checked || !this.modelValue);
        // eslint-disable-next-line no-unused-expressions
        !this.checked && window.navigator.vibrate(50);
      });
    },
    $onChange(callback) {
      !this.chandleHandles.includes(callback) && this.chandleHandles.push(callback);
    },
  },
};
</script>
<style scoped>
@property --underline-width {
  syntax: "<percentage>";
  inherits: false;
  initial-value: 0%;
}

.j-underline {
  background-image: linear-gradient(to left, #1890ff var(--underline-width), transparent var(--underline-width));
  background-repeat: no-repeat;
  background-size: 100% 2px;
  background-position: bottom;
  transition: --underline-width 0.6s linear;
}
.j-underline.active {
  background-image: linear-gradient(to right, #1890ff var(--underline-width), transparent var(--underline-width));
  --underline-width: 100%;
}
</style>
